import cv2
img_path="buttons.png"
src=cv2.imread(img_path)
cv2.imshow("Input",src)
oriImg=cv2.GaussianBlur(src,(5,5),0)
img=cv2.cvtColor(oriImg,cv2.COLOR_BGR2GRAY)
ret,img=cv2.threshold(img,250,255,cv2.THRESH_BINARY_INV)
cv2.imshow("Mask",img)
kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
img=cv2.dilate(img,kernel,iterations=1)
img=cv2.erode(img,kernel,iterations=1)
cv2.imshow("Morphology",img)
edges=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
cv2.imshow("Edges",edges)
contours,hierarchy=cv2.findContours(edges,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    x,y,w,h=cv2.boundingRect(contour)
    if w/h>0.7and w/h<1.3:
        cv2.rectangle(src,(x,y),(x+w,y+h),(0,0,255))
        cv2.imshow("Image",src)
        num_buttons=len(contours)
        print(f'检测到图像中的纽扣的数量:{num_buttons}')
        cv2.waitKey()
        cv2.destroyAllWindows()